package concurrent.automic;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.profile.StackProfiler;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * \* User: Administrator
 * <p>
 * \* Date: 2020/11/24
 * <p>
 * \* Time: 15:59
 * <p>
 * \* Description:
 * \
 */
//度量批次  10次
@Measurement(iterations = 10)
//预热批次 10次
@Warmup(iterations = 10)
//采用平均响应时间作为度量方式
@BenchmarkMode(Mode.AverageTime)
//时间单位为微秒
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class SynchronizedVsLockVsAtomicInteger {

    @State(Scope.Group)
    public static class IntMonitor{
        private int x;
        private Lock lock = new ReentrantLock();

        public void lockInc() {
            lock.lock();
            try {
                x++;
            } finally {
                lock.unlock();
            }
        }

        public void syncInc() {
            synchronized (this) {
                x ++;
            }
        }
    }

    @State(Scope.Group)
    public static class AtomicIntegerMonitor{
        private AtomicInteger i = new AtomicInteger(0);

        public void atomicInc() {
            i.incrementAndGet();
        }
    }

    @GroupThreads(10)
    @Group("sync")
    @Benchmark
    public void syncInc(IntMonitor monitor){
        monitor.syncInc();
    }

    @GroupThreads(10)
    @Group("lock")
    @Benchmark
    public void lockInc(IntMonitor monitor){
        monitor.lockInc();
    }

    @GroupThreads(10)
    @Group("atomic")
    @Benchmark
    public void atomicInc(AtomicIntegerMonitor monitor){
        monitor.atomicInc();
    }

    public static void main(String[] args) throws RunnerException {
        Options build = new OptionsBuilder().include(
                SynchronizedVsLockVsAtomicInteger.class.getSimpleName()
        ).forks(1).timeout(TimeValue.seconds(10)).addProfiler(StackProfiler.class)
                .build();
        new Runner(build).run();
    }
}
